package harsh.javatoxml.dom;

import java.util.Enumeration;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import harsh.javatoxml.data.IXMLElement;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class Domifier {

	public static Document toDom(IXMLElement document) throws ParserConfigurationException {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		Document doc = factory.newDocumentBuilder().newDocument();
		doc.appendChild(toDom(document,doc));
		return  doc;
	}
	
	private static Node toDom(IXMLElement element ,Document doc) {
		Element mirror = doc.createElement( element.getName() );
		Enumeration<String> attrs = element.enumerateAttributeNames();
		while (attrs.hasMoreElements()) {
			String attr = attrs.nextElement();
			mirror.setAttribute(attr, element.getAttribute(attr));	
		}
		
		Enumeration<IXMLElement> children = element.enumerateChildren();
		while(children.hasMoreElements()) {
			mirror.appendChild( toDom(children.nextElement(),doc));
		}
		if ((element.getContent() != null) && (element.getContent() != ""))
			mirror.appendChild(doc.createTextNode(element.getContent()));
		
		return mirror;
		}
		
	
}
